package com.ruoyi.web.controller.weather;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.exception.HttpResponseFailedException;
import com.ruoyi.system.keyStrategy.KeyUtils;
import com.ruoyi.system.weather.domain.Weather;
import com.ruoyi.system.weather.domain.WeatherWapper;
import com.ruoyi.system.weather.service.IWeatherService;
import com.ruoyi.web.controller.weather.request.WeatherRequest;
import com.ruoyi.web.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author xuezhenwei
 * @date 2024-06-16 10:12
 */
@RestController
@RequestMapping("/weather")
@Slf4j
public class WeatherController {

    @Autowired
    private HttpUtils httpUtils;

    @Autowired
    private IWeatherService iWeatherService;

    @Autowired
    private KeyUtils keyUtils;

    @GetMapping("/search")
//    @Retryable(value = {HttpResponseFailedException.class} , maxAttempts = 3, backoff = @Backoff(delay = 1000l, multiplier = 2,maxDelay = 1000l))
    public AjaxResult search(@Validated WeatherRequest weatherRequest) throws HttpResponseFailedException {

        String weatherInfoByKey = keyUtils.getWeatherInfoByKey(weatherRequest.getLocation());

        if (!StringUtils.isBlank(weatherInfoByKey)) {
            return AjaxResult.success("", weatherInfoByKey);
        }

//        String url = "https://devapi.qweather.com/v7/weather/now?" + "location=" + location + "&lang=" + lang + "&key=1884dba16bee49b2b137da1130cb7422" + "&unit=m" ;
        String url = "https://devapi.qweather.com/v7/weather/now";
        Map map = new HashMap();
        map.put("location", weatherRequest.getLocation());
        map.put("lang", weatherRequest.getLang());
        map.put("key", keyUtils.get());
        map.put("unit", "m");

        String result = httpUtils.httpUtil(map, url);
        WeatherWapper object = new WeatherWapper();

        try {
            object = (WeatherWapper) httpUtils.strToObject(result, WeatherWapper.class);
        } catch (Exception e) {
            log.error("解析异常 {}", e.getMessage());
        }
        if (Objects.isNull(object) || !StringUtils.equals(object.getCode(), "200")) {
            throw new HttpResponseFailedException();
        }


        if (!Objects.isNull(object) && !Objects.isNull(object.getCode()) && object.getCode().equals("200")) {
            Weather weather = object.getNow();
            if (!Objects.isNull(weather))
                try {
                    weather.setCityId(weatherRequest.getLocation());
                    weather.setCityName(weatherRequest.getCityName());
                    iWeatherService.insertWeather(weather);
                } catch (Exception e) {
                    log.error("保存天气信息出错！ {}", e.getMessage());
                }
        }

        keyUtils.setWeatherInfoByKey(weatherRequest.getLocation(), result);

        return AjaxResult.success("", result);
    }

    @GetMapping("/search7d")
    public AjaxResult search7d(@Validated WeatherRequest weatherRequest) throws HttpResponseFailedException {

        String weatherInfoByKey = keyUtils.getWeatherInfoByKey("7d" + weatherRequest.getLocation());
        if (!StringUtils.isBlank(weatherInfoByKey)) {
            return AjaxResult.success("", weatherInfoByKey);
        }
        String url = "https://devapi.qweather.com/v7/weather/7d";
        Map map = new HashMap();
        map.put("location", weatherRequest.getLocation());
        map.put("lang", weatherRequest.getLang());
        map.put("key", keyUtils.get());
        map.put("unit", "m");

        String result = httpUtils.httpUtil(map, url);
//        JSONObject object = JSONUtil.parseObj(result);
//        return AjaxResult.success(object.get("daily"));
        if (StringUtils.isNotBlank(result)) {
            keyUtils.setWeatherInfoByKey("7d" + weatherRequest.getLocation(), result, 60);
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/search24h")
    public AjaxResult search24d(@Validated WeatherRequest weatherRequest) throws HttpResponseFailedException {

        String weatherInfoByKey = keyUtils.getWeatherInfoByKey("24h" + weatherRequest.getLocation());

        if (!StringUtils.isBlank(weatherInfoByKey)) {
            return AjaxResult.success("", weatherInfoByKey);
        }
        String url = "https://devapi.qweather.com/v7/weather/24h";
        Map map = new HashMap();
        map.put("location", weatherRequest.getLocation());
        map.put("lang", weatherRequest.getLang());
        map.put("key", keyUtils.get());
        map.put("unit", "m");

        String result = httpUtils.httpUtil(map, url);
//        JSONObject object = JSONUtil.parseObj(result);
        if (StringUtils.isNotBlank(result)) {
            keyUtils.setWeatherInfoByKey("24h" + weatherRequest.getLocation(), result, 60);
        }
        return AjaxResult.success(result);
    }

    @GetMapping("/searchWarningInfo")
    public AjaxResult searchWarningInfo() throws HttpResponseFailedException {
        String url = "http://sdsqxt.cn:15010/products/yujing/yujing.php";
        Map map = new HashMap();
        map.put("cityname", "聊城");
        map.put("type", null);
        map.put("level", null);
        String result = httpUtils.httpUtil(map, url);
//        JSONObject object = JSONUtil.parseObj(result);
        return AjaxResult.success(result);
    }

    @GetMapping("/getValueByKey")
    public AjaxResult getValueByKey() {
        return AjaxResult.success("", keyUtils.getValueList());
    }

    @GetMapping("/setValueByKey")
    public AjaxResult getValueByKey(String key, Long value) {
        return AjaxResult.success("", keyUtils.setValueByKey(key, value));
    }

    /**
     * 空气质量每日预报API
     */
    @GetMapping("/search/air/quality")
    public AjaxResult searchAirQuality(String location){

        String weatherInfoByKey = keyUtils.getWeatherInfoByKey("search_air" + location);
        if (!StringUtils.isBlank(weatherInfoByKey)) {
            return AjaxResult.success("", weatherInfoByKey);
        }

        String url = "https://devapi.qweather.com/v7/air/5d";
        Map map = new HashMap();
        map.put("location", location);
        map.put("key", keyUtils.get());

        String result = httpUtils.httpUtil(map, url);
        if (StringUtils.isNotBlank(result)) {
            keyUtils.setWeatherInfoByKey("search_air" + location, result, 30);
        }
        return AjaxResult.success(result);
    }

}
